import 'dart:convert';
import 'package:flutter/services.dart';
import 'learning_item.dart';

class LearningDataService {
  /// 从JSON文件加载学习项数据
  static Future<List<LearningItem>> loadLearningItems() async {
    try {
      // 读取主JSON文件
      final String jsonString = await rootBundle.loadString(
        'assets/learning_data.json',
      );

      // 解析JSON数据
      final List<dynamic> jsonData = json.decode(jsonString);

      // 存储所有学习项
      final List<LearningItem> items = [];

      // 处理每个学习项
      for (var item in jsonData) {
        // 检查是否是引用类型的内容
        if (item['contentType'] != null && item['contentRef'] != null) {
          // 加载详细内容
          final detailedItems = await _loadAllDetailedContent(item);
          items.addAll(detailedItems);
        } else {
          // 普通内容直接添加
          items.add(_createLearningItem(item));
        }
      }

      return items;
    } catch (e) {
      // 如果加载失败，返回空列表
      print('Error loading learning items: $e');
      return [];
    }
  }

  /// 根据数据创建LearningItem对象
  static LearningItem _createLearningItem(Map<String, dynamic> item) {
    return LearningItem(
      id: item['id'],
      title: item['title'] ?? '',
      content: item['content'] ?? '',
      type: _parseContentType(item['type']),
      grade: item['grade'] ?? 1,
      subject: item['subject'] ?? '',
      module: item['module'] ?? '',
      difficulty: item['difficulty'] ?? 1,
      tags: List<String>.from(item['tags'] ?? []),
      questionData: item['questionData'] != null
          ? Map<String, dynamic>.from(item['questionData'])
          : null,
      contentRef: item['contentRef'],
      author: item['author'],
      dynasty: item['dynasty'],
      translation: item['translation'],
      formula: item['formula'],
      description: item['description'],
      example: item['example'],
    );
  }

  /// 解析内容类型
  static ContentType _parseContentType(dynamic type) {
    if (type is String) {
      switch (type) {
        case 'knowledge':
          return ContentType.knowledge;
        case 'question':
          return ContentType.question;
        case 'poem':
          return ContentType.poem;
        case 'math':
          return ContentType.math;
        default:
          return ContentType.knowledge;
      }
    }
    return ContentType.knowledge;
  }

  /// 加载详细内容中的所有项目
  static Future<List<LearningItem>> _loadAllDetailedContent(
    Map<String, dynamic> item,
  ) async {
    try {
      final contentRef = item['contentRef'];
      final contentType = item['contentType'];
      print("加载详细内容: $contentRef 类型: $contentType");
      // 尝试不同的路径加载详细内容文件
      // 构建并尝试不同的资源路径
      final List<String> potentialPaths = [
        'assets/content/$contentRef',
        'assets/content/yuwen_keben/$contentRef',
        'content/yuwen_keben/$contentRef',
        '$contentRef'
      ];

      String detailedJsonString;
      try {
        // 首先尝试完整路径
        if (contentType == 'chinese_textbook') {
          // 对于语文课文，直接在yuwen_keben目录下查找
          detailedJsonString = await rootBundle.loadString(
            'assets/content/yuwen_keben/$contentRef',
          );
        } else if (contentType == 'english_books') {
          // 对于英文故事书，直接在english_books目录下查找
          detailedJsonString = await rootBundle.loadString(
            'assets/content/english_books/$contentRef',
          );
        } else {
          detailedJsonString = await rootBundle.loadString(
            'assets/content/$contentRef',
          );
        }
      } catch (e) {
        print('Error loading detailed content1: $e');
        try {
          // 如果失败，尝试不带assets前缀的路径
          detailedJsonString = await rootBundle.loadString(
            'content/$contentRef',
          );
        } catch (e) {
          print('Error loading detailed content2: $e');
          try {
            // 再尝试yuwen_keben目录（不带assets前缀）
            detailedJsonString = await rootBundle.loadString(
              'content/yuwen_keben/$contentRef',
            );
          } catch (e) {
            print('Error loading detailed content3: $e');
            // 如果再次失败，尝试直接使用contentRef作为路径
            detailedJsonString = await rootBundle.loadString(contentRef);
          }
        }
      }

      // 特殊处理语文课本数据，它的结构是单个对象而不是数组
      dynamic detailedData = json.decode(detailedJsonString);
      
      final List<LearningItem> items = [];
      print("处理所有详细内容");
      // 处理所有详细内容
      if (contentType == 'chinese_textbook') {
        // 对于语文课本，直接处理单个对象
        final textbookItem = detailedData;
        
        // 处理语文课本内容
        // Chinese textbook files have a different structure - they contain a single object with a "textbook" property
        final textbookData = (textbookItem is Map<String, dynamic> && textbookItem.containsKey('textbook'))
            ? textbookItem['textbook']
            : textbookItem;

        if (textbookData != null) {
          // Handle the case where textbookData might be the root object itself
          final title = textbookData is Map<String, dynamic> ? textbookData['title'] : '语文课文';
          final publisher = textbookData is Map<String, dynamic> ? textbookData['publisher'] : '未知';
          final units = textbookData is Map<String, dynamic> 
              ? List<Map<String, dynamic>>.from(textbookData['units'] ?? []) 
              : [];

          // 为每个课文创建一个LearningItem
          for (var unit in units) {
            final lessons = List<Map<String, dynamic>>.from(
              unit['lessons'] ?? [],
            );

            // 为每个lesson创建一个LearningItem
            for (var lesson in lessons) {
              String lessonContent = '';
              if (lesson['content'] != null) {
                lessonContent = List<String>.from(lesson['content']).join('\n');
              }

              List<String> newChars = [];
              if (lesson['new_characters'] != null) {
                final characters = List<Map<String, dynamic>>.from(
                  lesson['new_characters'] ?? [],
                );
                for (var char in characters) {
                  newChars.add('${char['char']}(${char['pinyin']})');
                }
              }

              final learningItem = LearningItem(
                id: 'chinese_textbook_${contentRef}_${unit['unit_name']}_${lesson['title']}',
                title: '${title ?? '语文课文'}-${unit['unit_name']}-${lesson['title']}',
                content: lessonContent,
                type: ContentType.knowledge,
                grade: item['grade'] ?? 1, // 使用主数据中的年级
                subject: item['subject'] ?? '语文',
                module: item['module'] ?? '课文',
                difficulty: item['difficulty'] ?? 1,
                tags: List<String>.from(item['tags'] ?? []),
                contentRef: contentRef,
                description: '年级: ${item['grade'] ?? 1}\n'
                           '单元: ${unit['unit_name']}\n'
                           '新学汉字: ${newChars.join(', ')}',
                example: newChars.length.toString(), // 使用example字段存储新学汉字数量
              );

              items.add(learningItem);
            }
          }
        }
      } else {
        // 其他类型按原来的方式处理
        for (var detailedItem in detailedData) {
          // 合并主数据和详细数据
          // 详细数据优先，主数据作为默认值
          final mergedData = Map<String, dynamic>.from(item);

          // 根据内容类型处理特定字段映射
          if (contentType == 'poem') {
            // 处理古诗内容的字段映射
            mergedData['id'] = detailedItem['id'];
            mergedData['title'] =
                detailedItem['title_cns'] ?? mergedData['title'];
            mergedData['author'] =
                detailedItem['author_cns'] ?? mergedData['author'];
            mergedData['dynasty'] =
                detailedItem['dynasty_cns'] ?? mergedData['dynasty'];

            // 合并诗句内容
            if (detailedItem['paragraphs_cns'] != null) {
              List<String> paragraphs = List<String>.from(
                detailedItem['paragraphs_cns'],
              );
              mergedData['content'] = paragraphs.join('');
            }

            // 添加译文和标签
            mergedData['translation'] = detailedItem['translation'] ?? '';
            if (detailedItem['tags'] != null) {
              mergedData['tags'] = List<String>.from(detailedItem['tags']);
            }

            // 详细数据中的字段优先级更高
            _mergeFieldsWithPriority(mergedData, detailedItem);
          } else if (contentType == 'vocabulary') {
            // 处理词汇内容的字段映射 - 修正两层结构处理
            final vocabularyUnits = List<Map<String, dynamic>>.from(
              detailedItem['vocabulary'] ?? [],
            );

            // 为每个词汇单元创建一个LearningItem
            for (var unit in vocabularyUnits) {
              final words = List<Map<String, dynamic>>.from(
                unit['words'] ?? [],
              );

              final learningItem = LearningItem(
                id: 'vocabulary_unit_${detailedItem['vid']}_${unit['id']}',
                title: unit['title'] ?? 'Unit ${unit['id']}',
                content: 'Vocabulary Unit',
                type: ContentType.knowledge,
                grade: detailedItem['grade'] ?? item['grade'] ?? 1,
                subject: item['subject'] ?? 'English',
                module: item['module'] ?? 'Vocabulary',
                difficulty: item['difficulty'] ?? 1,
                tags: List<String>.from(item['tags'] ?? []),
                contentRef: 'vocabulary_data.json',
                description: unit['description'] ?? '',
                example: words.length.toString(), // 使用example字段存储词汇数量
              );

              items.add(learningItem);
            }
            
            continue; // 跳过下面的合并逻辑
          } else if (contentType == 'pinyin') {
            // 处理拼音内容的字段映射
            final symbols = List<Map<String, dynamic>>.from(
              detailedItem['symbols'] ?? [],
            );

            // 为每个拼音类型创建一个LearningItem
            final learningItem = LearningItem(
              id: 'pinyin_${detailedItem['id']}',
              title: detailedItem['title'] ?? '拼音',
              content: detailedItem['description'] ?? '拼音学习',
              type: ContentType.knowledge,
              grade: item['grade'] ?? 1,
              subject: item['subject'] ?? '语文',
              module: item['module'] ?? '拼音',
              difficulty: item['difficulty'] ?? 1,
              tags: List<String>.from(item['tags'] ?? []),
              contentRef: detailedItem['id'], // 使用拼音类型ID作为contentRef
              description: '${detailedItem['description']}\n包含${symbols.length}个${detailedItem['title']}',
              example: symbols.length.toString(), // 使用example字段存储符号数量
            );

            items.add(learningItem);
            continue; // 跳过下面的合并逻辑
          } else if (contentType == 'english_katong') {
            // 处理英文卡通内容的字段映射
            // 为每个英文卡通创建一个LearningItem
            final learningItem = LearningItem(
              id: 'english_katong_${detailedItem['id']}',
              title: detailedItem['name'] ?? '未知动画',
              content: detailedItem['synopsis'] ?? '', // 使用剧情简介作为内容
              type: ContentType.knowledge,
              grade: int.tryParse(detailedItem['grade'] ?? '1') ?? 1, // 使用grade作为年级
              subject: item['subject'] ?? 'English', // 从主数据获取学科
              module: item['module'] ?? 'Cartoon', // 从主数据获取模块
              difficulty: item['difficulty'] ?? 1, // 从主数据获取难度
              tags: List<String>.from(item['tags'] ?? []), // 从主数据获取标签
              contentRef: contentRef, // 使用contentRef
              description: '豆瓣评分: ${detailedItem['douban'] ?? '暂无'}\n'
                        '语言: ${detailedItem['language'] ?? '未知'}\n'
                        '时长: ${detailedItem['time'] ?? '未知'}\n'
                        '平台: ${detailedItem['platform'] ?? '未知'}',
            );

            items.add(learningItem);
            continue; // 跳过下面的合并逻辑
          } else if (contentType == 'film') {
            // 处理电影内容的字段映射
            // 为每个电影创建一个LearningItem
            final learningItem = LearningItem(
              id: 'film_${detailedItem['id']}',
              title: detailedItem['name'] ?? '未知电影',
              content: detailedItem['synopsis'] ?? '', // 使用剧情简介作为内容
              type: ContentType.knowledge,
              grade: int.tryParse(detailedItem['grade'] ?? '1') ?? 1, // 使用grade作为年级
              subject: item['subject'] ?? 'Film', // 从主数据获取学科
              module: item['module'] ?? 'Entertainment', // 从主数据获取模块
              difficulty: item['difficulty'] ?? 1, // 从主数据获取难度
              tags: List<String>.from(item['tags'] ?? []), // 从主数据获取标签
              contentRef: contentRef, // 使用contentRef
              description: '豆瓣评分: ${detailedItem['douban'] ?? '暂无'}\n'
                        '语言: ${detailedItem['language'] ?? '未知'}\n'
                        '时长: ${detailedItem['time'] ?? '未知'}\n'
                        '平台: ${detailedItem['platform'] ?? '未知'}',
            );

            items.add(learningItem);
            continue; // 跳过下面的合并逻辑
          } else if (contentType == 'english_books') {
            // 将英文内容和中文内容分别合并为字符串
            String englishContent = '';
            String chineseContent = '';
            
            if (detailedItem['e_content'] != null) {
              englishContent = List<String>.from(detailedItem['e_content']).join('\n\n');
            }
            
            if (detailedItem['c_content'] != null) {
              chineseContent = List<String>.from(detailedItem['c_content']).join('\n\n');
            }
          
            // 合并中英文内容作为完整内容
            String fullContent = '$englishContent\ne-c-content\n$chineseContent';
            
            final learningItem = LearningItem(
              id: 'english_story_${contentRef}_${detailedItem['e_title']}',
              title: detailedItem['e_title'] ?? detailedItem['c_title'] ?? '英文故事',
              content: fullContent,
              type: ContentType.knowledge,
              grade: item['grade'] ?? 1, // 使用主数据中的年级
              subject: item['subject'] ?? 'English',
              module: item['module'] ?? 'Stories',
              difficulty: item['difficulty'] ?? 1,
              tags: List<String>.from(item['tags'] ?? ['english', 'story']),
              contentRef: contentRef,
              description: detailedItem['c_title']?? '英文故事',
              example: detailedItem['e_title'] ?? '',
            );
            items.add(learningItem);
            continue; // 跳过下面的合并逻辑
        } else {
            // 其他类型内容使用默认合并方式
            mergedData['id'] = detailedItem['id'];
            mergedData.addAll(detailedItem);
          }

          items.add(_createLearningItem(mergedData));
        }

      }

      return items;
    } catch (e) {
      print('Error loading detailed content: $e');
      return [];
    }
  }

  /// 合并字段，详细数据优先
  static void _mergeFieldsWithPriority(
    Map<String, dynamic> base,
    Map<String, dynamic> priority,
  ) {
    priority.forEach((key, value) {
      base[key] = value;
    });
  }
}